import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { agencyAsync } from '@/appox/appox'
import { appoxEnums } from '@/appox/appox'

export const useConsoleProcedureStore = defineStore('consoleProcedure', () => {
  // 状态
  const consoleProcedureList = ref([])
  const selectedConsoleProcedureId = ref('')
  const isRunning = ref(false)
  const isAppIdle = ref(true)

  // 计算属性
  const hasProcedures = computed(() => consoleProcedureList.value.length > 0)
  const selectedProcedure = computed(() => 
    consoleProcedureList.value.find(procedure => procedure.id === selectedConsoleProcedureId.value)
  )
  const canRunProcedure = computed(() => hasProcedures.value && !isRunning.value && isAppIdle.value)

  // 动作
  async function initializeProcedurePanel() {
    await updateProcedureList()
  }

  async function updateProcedureList() {
    try {
      const consoleClassTable = await agencyAsync.getConsoleClassTable()
      
      if (!consoleClassTable) {
        consoleProcedureList.value = []
        selectedConsoleProcedureId.value = ''
        return
      }
      
      consoleProcedureList.value = Object.entries(consoleClassTable).map(([id, info]) => ({
        id,
        title: info.title
      }))

      if (consoleProcedureList.value.length > 0) {
        selectedConsoleProcedureId.value = consoleProcedureList.value[0].id
      } else {
        selectedConsoleProcedureId.value = ''
      }
    } catch (error) {
      console.error('Failed to update console procedure list:', error)
      consoleProcedureList.value = []
      selectedConsoleProcedureId.value = ''
    }
  }

  function selectProcedure(consoleClassId) {
    selectedConsoleProcedureId.value = consoleClassId
  }

  async function runProcedure() {
    if (!selectedConsoleProcedureId.value || isRunning.value) return

    try {
      isRunning.value = true
      await agencyAsync.runConsole(selectedConsoleProcedureId.value)
    } catch (error) {
      console.error('Failed to run procedure:', error)
    } finally {
      isRunning.value = false
    }
  }

  async function updateRunButton() {
    isAppIdle.value = await agencyAsync.getAppStatus() === appoxEnums.ApplicationStatus.Idle
  }

  return {
    // 状态
    procedureList: consoleProcedureList,
    selectedProcedureId: selectedConsoleProcedureId,
    isRunning,
    isAppIdle,
    // 计算属性
    hasProcedures,
    selectedProcedure,
    canRunProcedure,
    // 动作
    initializeProcedurePanel,
    updateProcedureList,
    selectProcedure,
    runProcedure,
    updateRunButton
  }
}) 